package com.zlq.cn.controller.api;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zlq.cn.annotations.ApiParamBean;
import com.zlq.cn.annotations.UnLogin;
import com.zlq.cn.annotations.UnSigned;
import com.zlq.cn.api.ApiMessage;
import com.zlq.cn.api.ApiParam;
import com.zlq.cn.api.ResponseException;
import com.zlq.cn.cache.RedisCacheService;
import com.zlq.cn.cache.RedisKey;
import com.zlq.cn.config.Config;
import com.zlq.cn.config.FinderConfiguration;
import com.zlq.cn.entity.BindUser;
import com.zlq.cn.entity.LocationLog;
import com.zlq.cn.entity.User;
import com.zlq.cn.service.un.*;
import com.zlq.cn.util.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhoucl
 * @since 2020-06-08
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private VipLogService vipLogService;
    @Autowired
    private LocationLogService locationLogService;
    @Autowired
    private BindUserService bindUserService;
    @Autowired
    private UserLableService userLableService;
    @Autowired
    private PushService pushService;
    @Autowired
    private RedisCacheService redisCacheService;
    @Autowired
    private FinderConfiguration finderConfiguration;

    @UnLogin
    @RequestMapping("/login")
    public Object login(@RequestBody ApiParam apiParam,
                        @Length(message = "手机号码不正确", min = 11, max = 11) String phone,
                        @Length(message = "验证码不正确", min = 4, max = 4) String vcode,
                        @NotNull(message = "平台不能为空") String platform) {
        if (!StringUtils.checkPhone(phone))
            ResponseException.resultApiError("手机号码格式不正确");
        if (!StringUtils.checkVcode(vcode))
            ResponseException.resultApiError("验证码格式不正确");
        return userService.updateLogin(phone, vcode, platform, false);
    }

    @RequestMapping("/updateUserInfo")
    public Object updateUserInfo(@RequestBody ApiParam apiParam, @ApiParamBean User user, User loginUser) {
        if (org.apache.commons.lang3.StringUtils.isAllEmpty(user.getAvatar(), user.getName(), user.getGender()))
            ResponseException.resultApiError("请至少修改一种");
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(user.getAvatar())) {
            loginUser.setAvatar(user.getAvatar());
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(user.getName())) {
            loginUser.setName(user.getName());
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(user.getGender())) {
            loginUser.setGender(user.getGender());
        }
        userService.updateUserAvatarAndNameAndGender(loginUser);
        return null;
    }

    @RequestMapping("/getUserInfo")
    public Object getUserInfo(@RequestBody ApiParam apiParam, User loginUser) {
        loginUser.setIsNotVipAddFriend(Config.IS_NOT_VIP_ADD_FRIEND);
        loginUser.setCurrentDate(LocalDateTime.now());
        return loginUser;
    }

    @RequestMapping("/getUserInfoByInvitationCode")
    public Object getUserInfoByInvitationCode(@RequestBody ApiParam apiParam, @NotBlank(message = "邀请码不能为空") String invitationCode, User loginUser) {
        User user = null;
        if (6 == invitationCode.length()) {
            user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getInvitationCode, invitationCode), false);
        } else if (11 == invitationCode.length()) {
            user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, invitationCode), false);
        }
        if (user == null) {
            ResponseException.resultApiError("该用户不存在");
        }
        user.setIsNotVipAddFriend(Config.IS_NOT_VIP_ADD_FRIEND);
        return user;
    }

    @RequestMapping("/userVipReport")
    public Object userVipReport(@RequestBody ApiParam apiParam,
                                @NotNull(message = "订单类型不能为空") String orderType,
                                @NotNull(message = "订单号不能为空") String orderNo,
                                @NotNull(message = "交易数据不能为空") String receipt,
                                User loginUser) throws Exception {
        vipLogService.saveUserVipReport(orderType, orderNo, receipt, loginUser);
        return null;
    }

    @UnSigned
    @RequestMapping("/userLocationReport")
    public Object userLocationReport(@RequestBody ApiParam apiParam, User loginUser,
                                     @NotNull(message = "纬度不能为空") Double latitude,
                                     @NotNull(message = "经度不能为空") Double longitude,
                                     @NotNull(message = "地址不能为空") String address,
                                     @NotNull(message = "电量不能为空") Integer battery,
                                     @NotNull(message = "网络类型不能为空") String networkType) {
        LocationLog locationLog = new LocationLog();
        locationLog.setUserId(loginUser.getId());
        locationLog.setLatitude(latitude);
        locationLog.setLongitude(longitude);
        locationLog.setAddress(address);
        locationLog.setBattery(battery);
        locationLog.setNetworkType(networkType);
        locationLog.setCreateTime(LocalDateTime.now());
        locationLog.setUpdateTime(LocalDateTime.now());
//        locationLogService.save(locationLog);
        LocationLogService.addLocationLog(locationLog);
        return null;
    }

    @UnSigned
    @RequestMapping("/userLocationReportList")
    public Object userLocationReportList(@RequestBody ApiParam apiParam, User loginUser, ArrayList<LocationLog> locationLogs) {
        if (!CollectionUtils.isEmpty(locationLogs)) {
            locationLogs.sort(LocationLogService::compare);
            for (LocationLog locationLog : locationLogs) {
                locationLog.setUserId(loginUser.getId());
                locationLog.setCreateTime(LocalDateTime.now());
                locationLog.setUpdateTime(LocalDateTime.now());
                LocationLogService.addLocationLog(locationLog);
            }
        }
        return null;
    }

    @RequestMapping("/userLableList")
    @UnLogin
    public Object userLableList(@RequestBody ApiParam apiParam) {
        return userLableService.list();
    }

    @RequestMapping("/userOnline")
    public Object userOnline(@RequestBody ApiParam apiParam, User loginUser) {
        if (loginUser.getIsOnline() != null && 0 == loginUser.getIsOnline()) {
            loginUser.setIsOnline(1);
            redisCacheService.set(RedisKey.createUserKey(loginUser.getId()), loginUser);
            userService.update(new UpdateWrapper<User>().setSql(true, "is_online = 1").eq("id", loginUser.getId()));
        }
        redisCacheService.set(RedisKey.createUserOnline(loginUser.getId()), "", finderConfiguration.getUserOnlineTimeout());
        return ApiMessage.resultApiMessage("刷新用户在线状态成功");
    }

    @RequestMapping("/bindUser")
    public Object bindUser(@RequestBody ApiParam apiParam, User loginUser,
                           @Length(message = "手机号码格式不正确", min = 11, max = 11) String phone,
                           @NotBlank(message = "称谓不能为空") String labelName) {
        if (!StringUtils.checkPhone(phone))
            ResponseException.resultApiError("手机号码格式不正确");
        bindUserService.saveBindUser(loginUser, phone, labelName);
        return ApiMessage.resultApiMessage("绑定成功");
    }

    @RequestMapping("/unBindUser")
    public Object unBindUser(@RequestBody ApiParam apiParam, User loginUser,
                             @NotNull(message = "绑定id不能为空") Integer bindId) {
        bindUserService.saveUnBindUser(loginUser, bindId);
        return ApiMessage.resultApiMessage("解除绑定成功");
    }

    @RequestMapping("/getBindUser")
    public Object getBindUser(@RequestBody ApiParam apiParam, User loginUser,
                              Integer page,
                              Integer pageSize) {
        return bindUserService.listByFromUserId(loginUser.getId(), page, pageSize);
    }

    @RequestMapping("/updateBindUserBatteryWarning")
    public Object updateBindUserBatteryWarning(@RequestBody ApiParam apiParam, User loginUser,
                                               @NotNull(message = "绑定id不能为空") Integer bindId,
                                               @NotNull(message = "电量预警不能为空") Integer batteryWarning) {
        bindUserService.lambdaUpdate().set(BindUser::getBatteryWarning, batteryWarning)
                .eq(BindUser::getId, bindId)
                .eq(BindUser::getFromUserId, loginUser.getId());
        return ApiMessage.resultApiMessage("电量预警修改成功");
    }

    @RequestMapping("/oneKeyPolice")
    public Object oneKeyPolice(@RequestBody ApiParam apiParam, User loginUser,
                               @NotNull(message = "用户ID不能为空") Integer userId) {
//        pushService.pushAccount(userId, "", "", null);
        return ApiMessage.resultApiMessage("报警成功");
    }

    @RequestMapping("/updateBindUserInfo")
    public Object updateBindUserInfo(@RequestBody ApiParam apiParam, User loginUser,
                                     @NotNull(message = "绑定id不能为空") Integer bindId,
                                     String avatar,
                                     String remark) {
        if (org.apache.commons.lang3.StringUtils.isAllEmpty(avatar, remark))
            return ApiMessage.resultApiMessage("修改成功");
        BindUser bindUser = new BindUser();
        bindUser.setAvatar(avatar);
        bindUser.setRemark(remark);
        bindUserService.update(bindUser, new LambdaUpdateWrapper<BindUser>()
                .eq(BindUser::getFromUserId, loginUser.getId())
                .eq(BindUser::getId, bindId));
        return ApiMessage.resultApiMessage("修改成功");
    }

}

